from paho.mqtt import client as mqtt_client
from time import sleep

broker = "47.109.75.129"

port = 1883
topic = "image"
# Generate a Client ID with the subscribe prefix.
client_id = '6828914b84adf27cda59adae_K210_CAMERA_0_1_2025051714'


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n" % rc)

    # client = mqtt_client.Client(client_id)
    client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION1, client_id)
    client.username_pw_set(username="K210_CAMERA", password="mynameisvan0")  # 设置用户名和密码
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        pass
    client.subscribe(topic)
    client.on_message = on_message


def publish(client, message):
    result = client.publish(topic, message)
    result: [0, 1]
    status = result[0]
    if status == 0:
        pass
    else:
        print(f"Failed to send message to topic {topic}")


def file_to_bytes(path_file):
    with open(path_file, 'rb') as f:
        image_bytes = f.read()
        return image_bytes


client = connect_mqtt()
subscribe(client)
client.loop_start()  # 非阻塞模式启动
img_bytes = file_to_bytes('IMG_20250506_183651.jpg')
block = int(len(img_bytes)/2048)
for i in range(block):
    publish(client, img_bytes[i*2048:(i+1)*2048])
    sleep(1)
publish(client, img_bytes[block*2048:])
print("传输完成")
while True:
    pass
